package net.xinqushi.design.interceptor.demo;

import java.io.IOException;
import java.util.Queue;

/**
 * @author xjie
 * @description
 */
public class ConcreteChain implements Chain{

    //拦截器列表
    Queue<Interceptor> queue;

    //原始Request信息
    Request request;
    public ConcreteChain(Queue<Interceptor> queue, Request request) {
        this.queue = queue;
        this.request = request;
    }
    @Override
    public Request request() {
        return this.request;
    }

    @Override
    public Response proceed(Request request) throws IOException {
        Interceptor interceptor = null;
        if (null != (interceptor = getNextInterceptor())){ // 迭代拦截器
            return interceptor.intercept(this);
        }
        // 此处的逻辑 可以处理为 1 、末尾拦截器必须返回一个结果  2 、 else之后执行请求逻辑
        throw new RuntimeException("last interceptor must have a response ! ");
    }

    Interceptor getNextInterceptor(){
        return queue.poll();
    }
}
